//
//  SportsViewController.m
//  LPSNews
//
//  Created by Ruan on 14-10-11.
//  Copyright (c) 2014年 LPS. All rights reserved.
//

#import "SportsViewController.h"
#import "SportsTableViewCell.h"
#import "SportsModel.h"
#import "TechDetailViewController.h"
#import "MJRefresh.h"
#import "AFHTTPRequestOperationManager.h"
#import "PhotoViewController.h"

#define SPORTS_URL @"http://c.3g.163.com/nc/article/list/T1348649079062/"
static int number = 0;
@interface SportsViewController ()
@property (nonatomic, retain) NSMutableArray * sportsContentArray;
@property (nonatomic,retain) NSMutableArray * temArray;
@property (nonatomic, assign)AFHTTPRequestOperationManager *requestManager;
@end

@implementation SportsViewController

-(void)dealloc
{
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
    [_requestManager.operationQueue cancelAllOperations];
    [_sportsContentArray release];
    [_temArray release];
    [super dealloc];
}



- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {

    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.tableView addHeaderWithTarget:self action:@selector(headerUpdata)];
    [self.tableView addFooterWithTarget:self action:@selector(footUpdata)];
}

- (void)headerUpdata
{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        NSString *headerUpdataString = [SPORTS_URL stringByAppendingFormat:@"%d-20.html",0];
        [self requestWebDataForURLString:headerUpdataString andIsDowndrag:YES];
    });
    
}

- (void)footUpdata
{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        NSString *footUpdataString = [SPORTS_URL stringByAppendingFormat:@"%d-20.html",number];
        [self requestWebDataForURLString:footUpdataString andIsDowndrag:NO];
    });
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _sportsContentArray.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *techCellStr = @"cell";
    
    SportsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:techCellStr];
    
    if (cell == nil) {
        
        cell = [[[SportsTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:techCellStr] autorelease];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    cell.spoImageView.image = nil;
    cell.titleLabel.text = nil;
    cell.sportsAccessibilityLabel.text = nil;
    cell.techBottomLine.backgroundColor = [UIColor clearColor];
    
    
    SportsModel *spoData = _sportsContentArray[indexPath.row];
    spoData.number = indexPath.row;
    cell.sports = spoData;
    
    return cell;
}



- (void)tableViewDownLoadDataForURLString:(NSString *)urlstring andIsDowndrag:(BOOL)isDowndrag
{
    if (_sportsContentArray == nil) {
        
        _sportsContentArray = [[NSMutableArray alloc] init] ;
        
        [self requestWebDataForURLString:urlstring andIsDowndrag:isDowndrag];
    }
}


- (void)requestWebDataForURLString:(NSString *)urlstring andIsDowndrag:(BOOL)isDowndrag

{
    NSMutableArray *requestDataArray = [[NSMutableArray alloc] init];
    AFHTTPRequestOperationManager *requestManager = [AFHTTPRequestOperationManager manager];
    self.requestManager = requestManager;
    
    [requestManager GET:urlstring  parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSDictionary *dict = responseObject;
        NSArray *keyarray = [dict allKeys];
        NSString *keyString = keyarray[0];
        NSArray *techArray = [dict objectForKey:keyString];
        
        for (NSDictionary * dic in techArray) {
            SportsModel * sports = [[SportsModel alloc] init];
            [sports setValuesForKeysWithDictionary:dic];
            [requestDataArray addObject:sports];
            [sports release];
        }
        
        if (isDowndrag) {
            
            self.sportsContentArray = requestDataArray;
            [self.tableView headerEndRefreshing];
            number = 20;
            
        }else
        {
            [self.sportsContentArray addObjectsFromArray:requestDataArray];
            number += 20;
            [self.tableView footerEndRefreshing];
        }
        
        [self.tableView reloadData];
        
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        UILabel *textLable = [[UILabel alloc] init];
        textLable.frame = CGRectMake(0, 0, 140, 100);
        textLable.center = CGPointMake(160, 240);
        textLable.backgroundColor = [UIColor darkGrayColor];
        textLable.text = @"网络不给力";
        textLable.textColor = [UIColor whiteColor];
        textLable.textAlignment = NSTextAlignmentCenter;
        textLable.layer.cornerRadius = 8;
        textLable.layer.masksToBounds = YES;
        [self.view.window addSubview:textLable];
        textLable.alpha = 0;
        [UIView animateWithDuration:0.1 animations:^{
            [UIView animateWithDuration:0.1 delay:0.2 options:UIViewAnimationOptionCurveLinear animations:^{
                textLable.alpha = 0.8;
            } completion:^(BOOL finished) {
                [UIView animateWithDuration:0.5 delay:1 options:UIViewAnimationOptionCurveLinear animations:^{
                    textLable.alpha = 0;
                } completion:^(BOOL finished) {
                    [textLable removeFromSuperview];
                }];
            }];
        }];
        
        [textLable release];
        
        [self.tableView headerEndRefreshing];
        [self.tableView footerEndRefreshing];
        
    }];
    
    [requestDataArray release];
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    SportsModel * sports = [_sportsContentArray objectAtIndex:indexPath.row];
    if (indexPath.row == 0) {
        return 210;
    }else
    {
        if (sports.imgType == 1) {
            return 160;
        }else
        {
            return 85;
        }
    }
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    SportsModel *techData = _sportsContentArray[indexPath.row];
    
    if (techData.photosetID == nil) {
        TechDetailViewController *techDetail = [[TechDetailViewController alloc] init];
        [self.navigationController pushViewController:techDetail animated:NO];
        
        techDetail.docid = techData.docid;
        
        [techDetail release];
    }
    else
    {
        PhotoViewController *photoDetail = [[PhotoViewController alloc] init];
        
        photoDetail.photosetID = techData.photosetID;
        [self.navigationController pushViewController:photoDetail animated:YES];
        
        [photoDetail release];
    }

    
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
